package com.htgd.gardenexpo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.htgd.gardenexpo.dao.GeConUserCompeteMapper;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConUserCompete;
import com.htgd.gardenexpo.entity.WxUser;
import com.htgd.gardenexpo.page.RecommendQuery;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.vo.RecommendVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 王秀田
 * @date: 2024/11/11 15:35
 * @description: 小程序 公共查询 热点推荐（热点，景观地标，智慧运动，展馆展览）
 */
@Api(tags = "小程序首页")
@RestController
@RequestMapping("/api/common")
@Slf4j
public class CommonController {

    @Autowired
    private CommonService commonService;

    @Autowired
    private GeConUserCompeteMapper geConUserCompeteMapper;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private WxUserCollectService wxUserCollectService;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private IGeConThemeActivityService geConThemeActivityService;


    @GetMapping(value = "/list")
    @ApiOperation("查询热点推荐")
    public CommonResult<List<RecommendVO>> recommendList(RecommendQuery recommendQuery, HttpServletRequest request) {
        CommonResult<List<RecommendVO>> result = new CommonResult<>();
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        log.info("小程序首页-热点推荐：{},{}",recommendQuery,openId);

        try {
            recommendQuery.setPageNum((recommendQuery.getPageNum() - 1) * recommendQuery.getPageSize());
            List<RecommendVO> list = new ArrayList<>();
            int count = 0;
            //全部
            if(Objects.equals(recommendQuery.getType(),"0")){
                list = commonService.getRecommendList(recommendQuery);
                list.stream().forEach(item-> {
                    if(Objects.equals(item.getType(),"1")){
                        Boolean collect = wxUserCollectService.isLike(openId, item.getNewId(),"scene");
                        if (collect) {
                            item.setIsLike(true);
                        }else{
                            item.setIsLike(false);
                        }
                    }
                });
                count = commonService.getRecommendCount(recommendQuery);
            }else if(Objects.equals(recommendQuery.getType(),"1")){//景观地标
                list = commonService.getSceneList(recommendQuery);
                list.stream().forEach(item-> {
                    Boolean collect = wxUserCollectService.isLike(openId, item.getNewId(),"scene");
                    if (collect) {
                        item.setIsLike(true);
                    }else{
                        item.setIsLike(false);
                    }
                });
                count = commonService.getSceneCount(recommendQuery);
            }
            else if(Objects.equals(recommendQuery.getType(),"2")){//原来的运动
                LocalDateTime now = LocalDateTime.now();
                list = commonService.getCalendarList(recommendQuery);
                list.stream().forEach(item->{
                    List<String> openIds = geConUserCompeteMapper.selectList(new LambdaQueryWrapper<GeConUserCompete>()
                            .eq(GeConUserCompete::getMotionId,item.getNewId())
                            .eq(GeConUserCompete::getStatus,"0")
                            .orderByDesc(GeConUserCompete::getCreateTime)
                            .last("limit 5")).stream().map(x->x.getOpenId()).collect(Collectors.toList());
                    Long num = geConUserCompeteMapper.selectCount(new LambdaQueryWrapper<GeConUserCompete>()
                            .eq(GeConUserCompete::getMotionId,item.getNewId())
                            .eq(GeConUserCompete::getStatus,"0"));
                    if(!openIds.isEmpty()){
                        item.setImages(wxUserService.list(
                                new LambdaQueryWrapper<WxUser>()
                                        .in(WxUser::getOpenId,openIds))
                                .stream().map(x->x.getUrl()).collect(Collectors.toList()));
                        item.setNum(num);
                    }else{
                        item.setNum(0L);
                        item.setImages(new ArrayList<>());
                    }
                    item.setActiveText(geBaseDictService.getTextByCodeAndValue("status_competition", item.getActive()));
                    if (now.isAfter(item.getStartDate()) && now.isBefore(item.getEndDate())) {
                        item.setActiveText("报名中");
                        item.setActive("3");
                    }
                });
                count = commonService.getCalendarCount(recommendQuery);
            }else if(Objects.equals(recommendQuery.getType(),"3")){//展馆展览
                list = commonService.getVenueList(recommendQuery);
                count = commonService.getVenueCount(recommendQuery);
            }else if(Objects.equals(recommendQuery.getType(),"4")){//主题活动
                list = geConThemeActivityService.getRecommendList(recommendQuery);
                count = list.size();
            }
            else{
                list = commonService.getRecommendList(recommendQuery);
                list.stream().forEach(item-> {
                    if(Objects.equals(item.getType(),"1")){
                        Boolean collect = wxUserCollectService.isLike(openId, item.getNewId(),"scene");
                        if (collect) {
                            item.setIsLike(true);
                        }else{
                            item.setIsLike(false);
                        }
                    }
                });
                count = commonService.getRecommendCount(recommendQuery);
            }
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(count));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/smartSportsList")
    @ApiOperation("查询智慧运动")
    public CommonResult smartSportsList(RecommendQuery recommendQuery) {
        log.info("智慧运动列表：{}",recommendQuery);
        return commonService.getSmartSportsList(recommendQuery);
    }

    @GetMapping(value = "/find")
    @ApiOperation("发现")
    public CommonResult find() {
        log.info("小程序首页-发现");
        return commonService.find();
    }

}
